<?php
/*

Copyright 2009 Matthew C. Dettinger

This program is free software: you can redistribute it and/or modify 
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

function dao_session_new_session($config, $user_uuid) {
	dao_session_expire_sessions($config);
	
	$link = c_establish_db_conn($config);
	$session_uuid = c_generate_uuid();
	$current_time = time();
	
	//check to see if group name is already in database
	$query = "INSERT INTO session VALUES('$session_uuid', '$user_uuid', '$current_time')";
	$result = mysqli_query($link, $query);
	
	return $session_uuid;
}

function dao_session_check_session($config, $_SESSION) {
	dao_session_expire_sessions($config);
	
	$link = c_establish_db_conn($config);
		
	$current_time = time();
	$query = "SELECT * FROM session WHERE uuid = '$_SESSION[session_uuid]'";
	$result = mysqli_query($link, $query);
	if(!mysqli_num_rows($result)) {
		// no session in db therefore session expired
		session_destroy();
		$msg = "Session has expired!";
		c_announce_user_error($msg);
	}
	
	while ($row = mysqli_fetch_assoc($result)) {
		$query = "UPDATE session SET time = '$current_time' WHERE uuid = '$_SESSION[session_uuid]'";
		mysqli_query($link, $query);
	}

}

function dao_session_expire_sessions($config) {
	$link = c_establish_db_conn($config);
	
	$current_time = time();
	$expire_time = $current_time - $config[session][expire_time];
	//echo $current_time." yea ".$expire_time;
	$query = "DELETE FROM session WHERE time < '$expire_time'";
	mysqli_query($link, $query);
	//echo mysqli_error($link);
}

?>